import { defineStore } from "pinia";
import { ref } from "vue";

export default defineStore('cart', () => {
    const cart = ref([]);
    const addToCart = goods => {
        const item = cart.value.find(item => goods.id === item.id);
        if (item) {
            item.num += goods.num;
        } else {
            cart.value.push({ ...goods, num: goods.num }); 
        }
    };
    const removeCart = id => {
        const index = cart.value.findIndex(item => item.id == id);
        if (index !== -1) {
            cart.value.splice(index, 1);
        }
    };
    const CartCount = () => {
        let sum = 0;
        cart.value.forEach(item => {
            sum += item.num;
        });
        return sum || null;
    };
    return { cart, addToCart, removeCart, CartCount };
}, {
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'cart',
                storage: localStorage
            }
        ]
    }
});


